<template>
  <div class="box">
    <div v-if="!disabled">
      <el-upload
        v-if="!(modelValue && modelValue?.length >= limit)"
        :action="baseUrlConfig.businessBaseUrl + '/fast/uploadFile'"
        :show-file-list="false"
        :before-upload="beforeUpload"
        :on-success="uploadSuccess"
        :accept="`.${accept.join(',.')}`"
      >
        <el-button icon="Upload">点击上传</el-button>
      </el-upload>
    </div>
    <div v-for="(item, i) in modelValue" :key="i" class="fileItem">
      <div @click="seeItem(item.resourceAddress)">
        <img
          :src="item.resourceAddress"
          alt=""
          v-if="
            ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'svg'].find(
              (item2) => item2 == item.enclosureSuffix
            )
          "
        />
        {{ item.enclosureContent }}
      </div>
      <el-icon v-if="!disabled" @click="deleteItem(i)"
        ><DeleteFilled
      /></el-icon>
    </div>
  </div>
</template>

<script setup>
import { ref, onBeforeMount, watch } from "vue";
import { ElMessage } from "element-plus";
import { baseUrlConfig } from "@/config/config";
const props = defineProps({
  // 数量
  limit: {
    type: Number,
    default: 1,
  },
  // 类型
  accept: {
    type: Array,
    default: () => [],
  },
  // 大小kb
  sizeKB: {
    type: Number,
    default: 1024 * 10,
  },
  // 是否禁用
  disabled: {
    type: Boolean,
    default: false,
  },
  // 手动实现v-model
  modelValue: {
    type: Array,
    default: () => [],
  },
  // 表单ref
  formRef: {
    type: Object,
  },
  // 绑定在form表单的key
  formKey: {
    type: String,
    default: "",
  },
});
// 其他类型处理数组
watch(
  () => props.modelValue,
  (newVal) => {
    if (!Array.isArray(newVal)) {
      updateModelValue("update:modelValue", []);
    }
  },
  {
    immediate: true,
    deep: true,
  }
);
const filesList = ref([]);
const updateModelValue = defineEmits(["update:modelValue"]);
const beforeUpload = (file) => {
  const name = file.name.split(".");
  if (!file) {
    return false;
  } else if (!props.accept.includes(name[1])) {
    ElMessage.error(`请上传${props.accept.join("/")}格式`);
    return false;
  }
  if (props.sizeKB * 1024 < file.size) {
    ElMessage.error(`上传文件不能超过${props.sizeKB / 1024}M`);
    return false;
  }
  return true;
};
const uploadSuccess = (response) => {
  if (response.code == 1) {
    let file = {
      enclosureCode: response.data.enclosureCode, // 文件编码
      enclosureContent:
        response.data.enclosureContent ||
        response.data.enclosureName + "." + response.data.enclosureSuffix, // 文件名
      enclosureName: response.data.enclosureName, //文件前缀
      enclosureSuffix: response.data.enclosureSuffix, // 文件后缀
      resourceAddress: response.data.resourceAddress,
    };
    console.log(file);
    props.modelValue.push(file);
    updateModelValue("update:modelValue", props.modelValue);
    // 手动处理表单校验
    if (props.formRef) {
      props.formRef.validateField(props.formKey);
    }
  } else {
    ElMessage.error(response.message || "上传失败");
  }
};
// 删除
const deleteItem = (index) => {
  props.modelValue.splice(index, 1);
  updateModelValue("update:modelValue", props.modelValue);
};
const seeItem = (url) => {
  window.open(url, "_blank");
};
</script>

<style lang="less" scoped>
.box {
  width: 100%;
  .fileItem {
    display: flex;
    justify-content: space-between;
    align-items: center;
    word-break: break-all;
    background-color: #ddd;
    padding: 0 5px;
    margin: 2px 0;
    color: #0078d7;
    & div {
      cursor: pointer;
      display: flex;
      align-items: center;
      img {
        width: 40px;
        height: 40px;
        margin: 5px 10px 5px 0;
      }
    }
    i {
      cursor: pointer;
      margin-left: 20px;
    }
  }
}
</style>
